//
//  LSNotiViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/18.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSNotiViewController.h"
#import "LSNotiTableViewCell.h"
#import "LSNewsViewModel.h"
#import "LSNewsDetailViewController.h"
#import "LSLoginViewController.h"

@interface LSNotiViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, assign) BOOL isFromTabbar;
@property (nonatomic, strong) UITableView *notiTableView;
@property (nonatomic, strong) NSMutableArray *dataArrayM;
@property (nonatomic, assign) int page;
@end

static NSString *LSNotiTableViewCellID = @"LSNotiTableViewCellID";

@implementation LSNotiViewController

- (instancetype)initWithTabbar:(BOOL)tabbar {
    self = [super init];
    if (self) {
        self.isFromTabbar = tabbar;
        if (!tabbar) {
            self.title = @"通知公告";
        }
    }
    return self;
}

- (void)presentLoginVC {
    LSLoginViewController *loginVC = [[LSLoginViewController alloc] init];
    HEBaseNavController *loginNav = [[HEBaseNavController alloc] initWithRootViewController:loginVC];
    loginNav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:loginNav animated:false completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (![UserInfoModel sharedInstance].isLogin || [[UserInfoModel sharedInstance].customerId isEqualToString:@""]) [self presentLoginVC];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.notiTableView];
    self.notiTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self loadData];
}

- (void)loadData {
    self.page = 1;
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:NotificationList param:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"pageNo":[NSString stringWithFormat:@"%d",self.page],@"count":@"10"} completionHandler:^(id responseObject, NSError *connectionError) {
        self.notiTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [self.notiTableView.mj_header endRefreshing];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray > 0) {
                    [self.dataArrayM removeAllObjects];
                    for (NSDictionary *dict in dataArray) {
                        LSNewsViewModel *model = [LSNewsViewModel mj_objectWithKeyValues:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    [self.notiTableView reloadData];
                }
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
        }
    }];
}

- (void)loadMoreData {
    self.page++;
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:NotificationList param:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"pageNo":[NSString stringWithFormat:@"%d",self.page],@"count":@"10"} completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            NSNumber *totalCount = responseObject[@"totalNum"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray > 0) {
                    for (NSDictionary *dict in dataArray) {
                        LSNewsViewModel *model = [LSNewsViewModel mj_objectWithKeyValues:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    if (self.dataArrayM.count >= totalCount.intValue) {
                        [self.notiTableView.mj_footer endRefreshingWithNoMoreData];
                    } else {
                        [self.notiTableView.mj_footer endRefreshing];
                    }
                    [self.notiTableView reloadData];
                }
            } else {
                self.page--;
                [self.notiTableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.page--;
            [self.notiTableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSNotiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSNotiTableViewCellID forIndexPath:indexPath];
    LSNewsViewModel *model = self.dataArrayM[indexPath.row];
    cell.mainImageName = @"notice";
    cell.mainTitleText = model.title;
    // iOS 生成的时间戳是10位
    NSTimeInterval interval = [model.releaseDate doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [formatter stringFromDate: date];
    cell.mainSubtitleText = dateString;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSNotiTableViewCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSNewsViewModel *model = self.dataArrayM[indexPath.row];
    LSNewsDetailViewController *newsDetailVC = [[LSNewsDetailViewController alloc] init];
    newsDetailVC.newsDetailID = model.id;
    [self.navigationController pushViewController:newsDetailVC animated:true];
}

- (UITableView *)notiTableView {
    if (!_notiTableView) {
        CGRect notiTableViewRect = CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight);
        if (self.isFromTabbar) {
            notiTableViewRect = CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-49);
        }
        _notiTableView = [[UITableView alloc] initWithFrame:notiTableViewRect];
        _notiTableView.backgroundColor = hexColor(EEEEEE);
        _notiTableView.separatorInset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
        _notiTableView.delegate = self;
        _notiTableView.dataSource = self;
        _notiTableView.tableFooterView = [UIView new];
        [_notiTableView registerClass:LSNotiTableViewCell.class forCellReuseIdentifier:LSNotiTableViewCellID];
    }
    return _notiTableView;
}

- (NSMutableArray *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
